import axios from 'axios'
import { MessageBox, Message } from 'element-ui'
import store from '@/store'
import { getToken } from '@/utils/auth'

// create an axios instance
const service = axios.create({
  // 开发环境：不使用baseURL，让请求走代理
  // 生产环境：使用环境变量中的API地址
  // baseURL: process.env.NODE_ENV === 'production' 
  //   ? (process.env.VUE_APP_BASE_API || '') 
  //   : '',
  baseURL:'',
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 5000 // request timeout
})

// request interceptor
service.interceptors.request.use(
  config => {
    // do something before request is sent

    if (store.getters.token) {
      // 根据API要求，在请求头中添加Authorization
      config.headers['Authorization'] = getToken()
      // 保留原有的X-Token以兼容其他可能的用例
      // config.headers['X-Token'] = getToken()
    }
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
  */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  response => {
    const res = response.data
    console.log('请求响应:', response.config.url, res)

    // 成功状态码是1
    if (res.code !== 1) {
      const errorMsg = res.massage || res.message || res.msg || 'Error'
      Message({
        message: errorMsg,
        type: 'error',
        duration: 5 * 1000
      })

      // token相关错误处理
      if (res.code==-1) {
        // to re-login
        MessageBox.alert('您的登录已过期，可以取消以停留在此页面，或重新登录', '确认登出', {
          confirmButtonText: '重新登录',
          type: 'warning'
        }).then(() => {
          store.dispatch('user/resetToken').then(() => {
            location.reload()
          })
        })
      }
      return Promise.reject(new Error(errorMsg))
    } else {
      return res
    }
  },
  error => {
    console.error('请求错误:', error) // for debug
    console.error('错误响应:', error.response)
    if (error.response) {
      console.error('错误响应数据:', error.response.data)
      console.error('错误状态码:', error.response.status)
    }
    const errorMsg = error.response?.data?.massage || error.response?.data?.message || error.response?.data?.msg || error.message || '请求失败'
    Message({
      message: errorMsg,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

export default service
